package com.pen.sample.client.model.delegate;

import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Timer;

public class MockStocksDelegate implements IDelegate
{

	@Override
	public void get( String url )
	{
		get( url, null );
	}

	@Override
	public void get( final String url, final IResponder callback )
	{
		if ( callback == null )
			return;

		// Ignore the URL
		Timer t = new Timer()
		{
			@Override
			public void run()
			{
				String json = "[";

				NumberFormat nf = NumberFormat.getDecimalFormat();
				String[] symbols;
				try
				{
					String s = url.substring( url.indexOf( "?" ) + 1 );
					symbols = s.split( "\\+" );
				}
				catch ( Exception e )
				{
					symbols = new String[1];
					symbols[0] = url.substring( url.indexOf( "?" ) + 1 );
				}
				for ( String symbol : symbols )
				{
					Double price = Math.random() * 100;
					Double change = price * 0.02f * ( Math.random() * 2.0f - 1.0f );
					json += "{\"symbol\": \"" + symbol + "\", \"price\": " + nf.format( price ) + ", \"change\": " + nf.format( change ) + "},";
				}
				json = json.substring( 0, json.length() - 1 );
				json += "]";

				callback.onResponse( new Result( true, null, json ) );
			}
		};
		t.schedule( 1500 );
	}

}
